package animix.blue.server.log.service.impl;

import animix.blue.server.common.bean.model.LogOperation;
import animix.blue.server.common.bean.pojo.Result;
import animix.blue.server.common.bean.tool.PagedList;
import animix.blue.server.common.bean.tool.Pagination;
import animix.blue.server.common.utils.HttpUtils;
import animix.blue.server.log.mapper.LogOperationMapper;
import animix.blue.server.log.service.LogOperationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class LogOperationServiceImpl implements LogOperationService {

    @Autowired
    private LogOperationMapper logOperationMapper;

    /**
     * 方法不能有返回值
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "queue.blue.log.operation", durable = "true"),
            exchange = @Exchange(value = "exchange.direct", durable = "true"), key = "KEY_LOG_OPERATION")})
    @Override
    public void save(LogOperation logOperation) {
        try {
            // 通过IP获取地址
            logOperation.setLocation(HttpUtils.getAddresses(logOperation.getIp()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 插入数据
            logOperationMapper.insert(logOperation);
        }
    }

    @Override
    public Result list(Map<String, Object> para) {
        // 分页插件
        Integer currentPage = para.get("currentPage") == null ? 1 : Integer.parseInt((String) para.get("currentPage"));
        Integer pageSize = para.get("pageSize") == null ? 10 : Integer.parseInt((String) para.get("pageSize"));
        PageHelper.startPage(currentPage, pageSize);
        // 查询
        List<LogOperation> list = logOperationMapper.list(para);
        // 分页信息
        PageInfo pageInfo = new PageInfo(list);
        Pagination pagination = new Pagination();
        pagination.setCurrent(currentPage);
        pagination.setPageSize(pageSize);
        pagination.setTotal(pageInfo.getTotal());
        // 包装
        PagedList<LogOperation> pagedList = new PagedList();
        pagedList.setList(list);
        pagedList.setPagination(pagination);
        // 返回
        return Result.ok(pagedList);
    }
}
